// pages/guide/guide.js
import { getWechatProPhoneIdByCode, bpaiLogin } from '../../api/index'
import { setTokenValue, getTokenValue, setUserInfo, removeTokenValue } from '../../utils/storage'
import { showLoading, showToast, hideLoading } from '../../utils/toast'
import { trackingEventMap, trackingEvent } from '../../utils/tracking'
import { adRequest } from '../../utils/request'
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    redirectUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.logout && options.logout == 1) {
      removeTokenValue()
    }
    if (options.redirectUrl) {
      this.setData({
        redirectUrl: options.redirectUrl
      })
    }
  },
  // 获取手机号code
  async getphonenumber(e) {
    await trackingEvent(trackingEventMap.getPhone)
    if (e.detail.code) {
      try {
        showLoading('手机号获取中')
        let result = await getWechatProPhoneIdByCode({ code: e.detail.code })
        hideLoading()
        this.setData({
          phone: result.phoneNumber
        })
        this.confirmData()
      } catch (error) {
        setTimeout(() => {
          hideLoading()
        }, 3000)
      }
    }
  },
  async confirmData() {
    Dialog.confirm({
      title: '您提供的手机号将用于登录BPai智能咨询',
      message: '您是否确认并继续使用BPai咨询',
      confirmButtonColor: '#2A64F6',
      beforeClose: (action) => new Promise(async (resolve) => {
        if (action === 'confirm') {
          let phone = this.data.phone
          let redirectUrl = this.data.redirectUrl
          const globalData = getApp().globalData
          try {
            let loginResult = await bpaiLogin({
              channelCode: globalData.extraMsg.channelCode || '',
              inviterCode: globalData.extraMsg.inviterCode || '',
              sourceTag: globalData.extraMsg.sourceTag || '',
              phone,
              regChannel: 'BPai_applet'
            })
            setTokenValue(loginResult.token)
            resolve(true);
            let sourceTag = 1
            if (globalData.activityConfig.activitySwitch == '1') {
              sourceTag = 2
            }
            wx.redirectTo({
              url: `/pages/chatView/chatView?sourceTag=${sourceTag}&redirectUrl=${redirectUrl}`
            })
            if (loginResult.newUserTag && globalData.gdtVid) {
              await adRequest({
                gdtVid: globalData.gdtVid,
                actionType: "REGISTER"
              })
            }
            await trackingEvent(trackingEventMap.phoneAuthLogin)
          } catch (error) {
            resolve(false);
          }

        } else {
          // 拦截取消操作
          await trackingEvent(trackingEventMap.phoneAuthCancel)
          resolve(true);
        }
      })
    }).then(() => {
      // on confirm
    })
      .catch(() => {
        // on cancel
      });
  },
  goChatView() {
    wx.redirectTo({
      url: '/pages/chatView/chatView'
    })
  },
  goExperience() {
    wx.redirectTo({
      url: '/pages/chatExperience/chatExperience'
    })
  },
  goLogin() {
    let redirectUrl = this.data.redirectUrl
    wx.navigateTo({
      url: `/pages/login/login?redirectUrl=${redirectUrl}`
    })
    trackingEvent(trackingEventMap.phoneAuthCancel)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (getTokenValue()) {
      this.goChatView()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})